[][src]Crate smol

A small and fast async runtime.

Executors

There are three executors that poll futures:

  1. Thread-local executor for tasks created by Task::local().
  2. Work-stealing executor for tasks created by Task::spawn().
  3. Blocking executor for tasks created by Task::blocking(), blocking!, iter(), reader() and writer().

Blocking executor is the only one that spawns threads on its own.

See here for how to run executors on a single thread or on a thread pool.

Reactor

To wait for the next I/O event, the reactor calls epoll on Linux/Android, kqueue on macOS/iOS/BSD, and wepoll on Windows.

The Async type registers I/O handles in the reactor and is able to convert their blocking operations into async operations.

The Timer type registers timers in the reactor that will fire at the chosen points in time.

Running

Function run() simultaneously runs the thread-local executor, runs the work-stealing executor, and polls the reactor for I/O events and timers. At least one thread has to be calling run() in order for futures waiting on I/O and timers to get notified.

If you want a multithreaded runtime, just call run() from multiple threads. See here for an example.

There is also block_on(), which blocks the current thread until a future completes, but it doesn't poll the reactor or run executors. When using block_on(), make sure at least one thread is calling run(), or else I/O and timers will not work!

Blocking tasks run in the background on a dedicated thread pool.

Examples

Connect to a HTTP website, make a GET request, and pipe the response to the standard output:

use futures::prelude::*;
use smol::Async;
use std::net::TcpStream;

fn main() -> std::io::Result<()> {
    smol::run(async {
        let mut stream = Async::<TcpStream>::connect("example.com:80").await?;
        let req = b"GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n";
        stream.write_all(req).await?;

        let mut stdout = smol::writer(std::io::stdout());
        futures::io::copy(&stream, &mut stdout).await?;
        Ok(())
    })
}

Look inside the examples directory for more: a web crawler, a Ctrl-C handler, a TCP client/server, a TCP chat client/server, a TLS client/server, an HTTP+TLS client/server, an async-h1 client/server, a hyper client/server, and a WebSocket+TLS client/server.

It's also possible to plug non-async libraries into the runtime: see inotify, timerfd, signal-hook, and uds_windows.

Finally, there's an example showing how to use smol with async-std, tokio, surf, and reqwest.

Macros

blocking

Spawns blocking code onto a thread.

Structs

Async

Async I/O.

Task

A spawned future.

Timer

Fires at the chosen point in time.

Functions

block_on

Blocks on a single future.

iter

Creates a stream that iterates on a thread.

reader

Creates an async reader that runs on a thread.

run

Runs executors and polls the reactor.

writer

Creates an async writer that runs on a thread.